package com.socket.test1;

import com.suanfa.sort.Selection;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by buguniao on 16/4/13.
 */
public class NIOServer {
    public static void main(String[] args) throws Exception{
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(8080));
        serverSocketChannel.configureBlocking(false);

        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);


        while(true){
            selector.select();
            System.out.println("已经有socket准备好了");
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> it = keys.iterator();

            while (it.hasNext()){
                SelectionKey key = it.next();
                it.remove();

                if(key.isAcceptable()){
                    ServerSocketChannel server = (ServerSocketChannel)key.channel();
                    SocketChannel client = server.accept();

                    client.configureBlocking(false);
                    SelectionKey key1 = client.register(selector, SelectionKey.OP_READ);
                    List<Byte> list = new ArrayList<Byte>();
                    key1.attach(list);
                }else if(key.isWritable()){

                }else if(key.isReadable()){
                    List<Byte> list = (List<Byte>)key.attachment();
//                    SocketChannel channel = key.channel();
                }
            }
        }
    }
}
